//
// Created by wormtql on 2020/11/7.
//
#include <map>
#include <set>
#include <cstring>
#include <string>
#include <fstream>

#define MAGIC "128318798d7f89sf7w8e21"

using namespace std;

set<string> ha;

int dup_edge_count = 0;
int edge_count = 0;

ofstream out_file;

bool parseLine(const char * line, char * from, char * to) {
    int i = 0;
    bool flag = false;
    bool isFrom = true;

    int a = 0;
    int b = 0;

    while (line[i] != '\0') {
        if (line[i] == '\"') {
            if (!flag) {
                flag = true;
            } else {
                if (!isFrom) {
                    break;
                }
                flag = false;
                isFrom = false;
            }
            i++;
            continue;
        }

        if (flag) {
            if (isFrom) {
                from[a] = line[i];
                a++;
            } else {
                to[b] = line[i];
                b++;
            }
        }
        i++;
    }

    if (a == 0 || b == 0) {
        return false;
    }
    edge_count++;

    from[a] = 0;
    to[b] = 0;

    char buf[1000] = { 0 };
    strcat(buf, from);
    strcat(buf, MAGIC);
    strcat(buf, to);

    string temp(buf);

    if (ha.find(temp) == ha.end()) {
        ha.insert(temp);
        return true;
    } else {
        dup_edge_count++;
    }
    return false;
}

void processFile(const char * filename) {
    ifstream file(filename);

    char buf[1000] = { 0 };
    while (file.getline(buf, 1000)) {
        char from[100] = { 0 };
        char to[100] = { 0 };
        bool ret = parseLine(buf, from, to);

        if (ret) {
//            printf("\"%s\" -> \"%s\"\n", from, to);
            out_file << "\"" << from << "\" -> \"" << to << "\"" << endl;
        }
    }

    file.close();
}

int main(int argc, char * argv[]) {
    if (argc < 3) {
        printf("usage: app <outfile> <trace1> ... <tracen>");
        return 0;
    }
    out_file.open(argv[1]);

    for (int i = 2; i < argc; i++) {
        processFile(argv[i]);
    }
    printf("edge count: %d\n", edge_count);
    printf("duplicate edge count: %d\n", dup_edge_count);
    printf("merge rate: %.6lf\n", (1.0 * edge_count - dup_edge_count) / (edge_count));

    out_file.close();

    return 0;
}